
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { AgGridReact } from 'ag-grid-react';
import { Button, Checkbox, message, Popover, Switch } from 'antd';
import "../sass/table.scss"
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import { setDefaultData, setChangeVauleList, setErrorList } from "../reducer/parseResult"
import parseService from "../service/parseResult/parseResultService"
import Item from 'antd/lib/list/Item';
export default function Table(this: any, props: any) {
    const dispatch = useDispatch()
    //单元格样式
    const cellStyle = (params: any) => {
        if (params.data.isCorrect === false) { //如果发行人名称不匹配
            return {
                background: "rgb(228, 116, 112)",
                color: "white"
            }
        }
    };
    const cellStongStyle = (params: any) => {
        if ((/[0-9]./).test(params.data.first)) {
            return {
                fontWeight: 600
            }
        }
    }
    //是否可以编辑
    const canEdit = (params: any) => {
        if (params.data.key == 0) {
            return false
        } else {
            return isEdit
        }
    }
    const ErrorList = useSelector((state: any) => state.ParseResult.ErrorList) //获取错误列表


    //单元格提示信息
    const cellRender = (params: any) => {

        let first = params.data.first.split("|")[1] ? params.data.first.split("|")[1] : params.data.first.split("|")[0]
        let second = params.data.second ? params.data.second.split("|")[1] ? params.data.second.split("|")[1] : params.data.second.split("|")[0] : ""
        //获取该列对应的field
        let field = params.colDef.field
        //判断是否为只能填入数字的列
        if (["firstTable", "firstTables", "firsttables", "secondTable", "secondTables", "secondtables"].some((item: string) => item == field)) {
            //是，分情况返回相应的html结构
            if (params.value == "" || params.value * 1 == params.value || params.data.key == 0) {
                //如果是空值或者数字直接返回
                switch (field) {
                    case "firstTable": {
                        return <div id={first.trim() + "-本期"}>{params.value}</div>
                    } case "firstTables": {
                        return <div id={first.trim() + "-上期"} >{params.value}</div>
                    } case "firsttables": {
                        return <div id={first.trim() + "-上上期"} >{params.value}</div>
                    } case "secondTable": {
                        return <div id={second.trim() + "-本期"} >{params.value}</div>
                    } case "secondTables": {
                        return <div id={second.trim() + "-上期"} >{params.value}</div>
                    } case "secondtables": {
                        return <div id={second.trim() + "-上上期"} >{params.value}</div>
                    }
                    default: {
                        return <div></div>
                    }

                }

            }
            //如果是其他数据类型则报错
            else {
                switch (field) {
                    case "firstTable": {
                        return <div id={first.trim() + "-本期"}>
                            <Popover content={"数据格式不正确"} trigger="hover" className={"numberForm"}>
                                <div style={{ width: "100%", color: "Red" }}> {params.value}</div>
                            </Popover></div>
                    } case "firstTables": {
                        return <div id={first.trim() + "-上期"}>
                            <Popover content={"数据格式不正确"} trigger="hover" className={"numberForm"}>
                                <div style={{ width: "100%", color: "Red" }}> {params.value}</div>
                            </Popover></div>
                    } case "firsttables": {
                        return <div id={first.trim() + "-上上期"}>
                            <Popover content={"数据格式不正确"} trigger="hover" className={"numberForm"}>
                                <div style={{ width: "100%", color: "Red" }}> {params.value}</div>
                            </Popover></div>
                    } case "secondTable": {
                        return <div id={second.trim() + "-本期"}>
                            <Popover content={"数据格式不正确"} trigger="hover" className={"numberForm"}>
                                <div style={{ width: "100%", color: "Red" }}> {params.value}</div>
                            </Popover></div>
                    } case "secondTables": {
                        return <div id={second.trim() + "-上期"}>
                            <Popover content={"数据格式不正确"} trigger="hover" className={"numberForm"}>
                                <div style={{ width: "100%", color: "Red" }}> {params.value}</div>
                            </Popover></div>
                    } case "secondtables": {
                        return <div id={second.trim() + "-上上期"}>
                            <Popover content={"数据格式不正确"} trigger="hover" className={"numberForm"}>
                                <div style={{ width: "100%", color: "Red" }}> {params.value}</div>
                            </Popover></div>
                    } default: {
                        return <div></div>
                    }

                }


            }
        }

    }
    const containerStyle = useMemo(() => ({
        width: '100%', height: '100%'
    }), []);
    //设置行宽度
    const [rowWidht, setRowWidht] = useState(0)
    //父元素传过来的参数
    const { data, columnType, rowHeight, isThree, projectId, errorList } = props

    let datasource = data.concat()

    const defaultData = useSelector((state: any) => state.ParseResult.defaultData) //被修改的行

    const changeValueList = useSelector((state: any) => state.ParseResult.changeVauleList)
    const [columnRef, setColumRef] = useState<Array<any>>([])
    const [isEdit, setIsEdit] = useState(false)//是否可以编辑
    const [needCommit, setNeedCommit] = useState(false) //是否需要提交到后端数据库
    const [errorOpen, setErrorOpen] = useState(false)//展开勾稽关系
    const gridRef: any = useRef() //gird

    const errorColRef = [
        {
            field: "选择",
            minWidth: 70,
            maxWidth: 70,
            lockPosition: true,
            headerCheckboxSelectionFilteredOnly: true,
            checkboxSelection: true,

        }, {
            headerName: "勾稽关系错误",
            field: "error_info",
            minWidth: 300,
            maxWidth: 300,
            lockPosition: true,
            cellClass: "cell-wrap-text",
            autoHeight: true,

        }, {
            field: "error_key_list",
            headerName: "相关科目",
            minWidth: 400,
            maxWidth: 400,
            cellClass: "cell-wrap-text",
            lockPosition: true,
            autoHeight: true,
            cellRenderer(params: any) {
                return params.data.error_key_list.map((item: any, index: number) => {
                    return <Button key={index} size={"small"} style={
                        {
                            marginRight: 10
                        }
                    } onClick={(e: any) => {
                        let anchorElement = document.getElementById(e.target.innerText);
                        if (anchorElement) {
                            anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
                        }
                        console.log(e.target.innerText);
                        console.log(params);
                    }}>{item} </Button>
                })
            }
        }
    ]
    useEffect(() => {
        //console.log(ErrorList);

        if (columnType == "审计意见解析") {
            column = columnData[columnType]
            setColumRef(columnData[columnType])
        } else if (["合并资产负债表", "母公司资产负债表"].some((item: string) => item == columnType)) {
            isThreeYearReport("doubuleTable")
        } else if (["合并利润表", "合并现金流量表", "母公司利润表", "母公司现金流量表"].some((item: string) => item == columnType)) {
            isThreeYearReport("oneTable")
        } else if (columnType == "自填数据") {
            isThreeYearReport("自填数据")
        } else if (columnType == "现金流量表补充资料") {
            isThreeYearReport("现金流量表补充资料")
        }
        //   console.log(column);

        // 

    }, [ErrorList])
    //勾稽关系错误单元格样式
    const cellstyle = (params: any) => {
        // console.log(params);

        // let first = params.data.first.split("|")[1] ? params.data.first.split("|")[1] : params.data.first.split("|")[0]
        // let second = params.data.second ? params.data.second.split("|")[1] ? params.data.second.split("|")[1] : params.data.second.split("|")[0] : ""
        //获取该列对应的field
        let field = params.colDef.field
        switch (field) {
            case "firstTable": {

                if (ErrorList.some((item: any) => item == (params.data.first.trim().split("|")[1] ? params.data.first.trim().split("|")[1] : params.data.first.trim().split("|")[0]) + "-本期")) {
                    return {
                        background: "rgb(228,116,112)",
                        color: "white"
                    }
                } else {
                    return {

                    }
                }
            } case "firstTables": {
                if (ErrorList.some((item: any) => item == (params.data.first.trim().split("|")[1] ? params.data.first.trim().split("|")[1] : params.data.first.trim().split("|")[0]) + "-上期")) {
                    return {
                        background: "rgb(228,116,112)",
                        color: "white"
                    }
                } else {
                    return {

                    }
                }
            } case "firsttables": {
                if (ErrorList.some((item: any) => item == (params.data.first.trim().split("|")[1] ? params.data.first.trim().split("|")[1] : params.data.first.trim().split("|")[0]) + "-上上期")) {
                    return {
                        background: "rgb(228,116,112)",
                        color: "white"
                    }
                } else {
                    return {

                    }
                }
            } case "secondTable": {
                if (ErrorList.some((item: any) => item == (params.data.second.trim().split("|")[1] ? params.data.second.trim().split("|")[1] : params.data.second.trim().split("|")[0]) + "-本期")) {
                    return {
                        background: "rgb(228,116,112)",
                        color: "white"
                    }
                } else {
                    return {

                    }
                }
            } case "secondTables": {
                if (ErrorList.some((item: any) => item == (params.data.second.trim().split("|")[1] ? params.data.second.trim().split("|")[1] : params.data.second.trim().split("|")[0]) + "-上期")) {
                    return {
                        background: "rgb(228,116,112)",
                        color: "white"
                    }
                } else {
                    return {

                    }
                }
            } case "secondtables": {
                if (ErrorList.some((item: any) => item == (params.data.second.trim().split("|")[1] ? params.data.second.trim().split("|")[1] : params.data.second.trim().split("|")[0]) + "-上上期")) {
                    return {
                        background: "rgb(228,116,112)",
                        color: "white"
                    }
                } else {
                    return {

                    }
                }
            }
        }
        // if (params.colDef.field == "firstTable" || params.colDef.field == "secondTable") {
        //     //本期
        //     console.log(params.data.first + "-本期");

        //     if (ErrorList.some((item: any) => item == params.data.first + "-本期") && params.colDef.field == "firstTable") {
        //         return {
        //             background: "blue"
        //         }
        //     }

        // } else {
        //     return {
        //         background: "red"
        //     }
        // }
    }
    //表头过滤
    const valueFormatter = (params: any) => {
        if (params.data.first) {
            return params.data.first.split("|")[0]
        }
        if (params.data.second) {
            return params.data.second.split("|")[0]
        }
    }
    const numberFormatter = (params: any) => {
        if (params.value * 1 == params.value) {
            return (params.value * 1).toFixed(2)
        }
    }
    //错误数据的行数列表
    const [errorRow, setErrorRow] = useState<Array<number>>([])
    //列表头
    const columnData: any = {
        "审计意见解析": [
            {
                field: "resType",
                minWidth: 100,
                maxWidth: 300,

            }, {
                field: "value",
                editable: isEdit,
                minWidth: 100,
                cellStyle: cellStyle,
                maxWidth: 300,
                cellRenderer: (params: any) => {
                    if (params.data.isCorrect === false) { //如果发行人名称不匹配
                        return <Popover content={"发行人名称不匹配"} trigger="hover"
                        >
                            <div style={{ width: "100%" }}> {params.value}</div>
                        </Popover>
                    } else {
                        return params.value
                    }
                }
            }
        ],
        "doubuleTable": [
            {
                field: "first",
                minWidth: 300,
                maxWidth: 300,
                valueFormatter
            }, {
                field: "firstTable",
                editable: canEdit,
                minWidth: 200,
                maxWidth: 200,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter
            }, {
                field: "firstTables",
                minWidth: 200,
                maxWidth: 200,
                editable: canEdit,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter
            },
            {
                field: "second",
                minWidth: 300,
                maxWidth: 300,
                valueFormatter,


            }, {
                field: "secondTable",
                minWidth: 200,
                maxWidth: 200,
                editable: canEdit,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter

            }, {
                field: "secondTables",
                minWidth: 200,
                maxWidth: 200,
                editable: canEdit,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter
            }
        ],
        "oneTable": [{
            field: "first",
            minWidth: 375,
            maxWidth: 375, valueFormatter
        }, {
            field: "firstTable",
            editable: canEdit,
            minWidth: 200,
            maxWidth: 200,
            cellRenderer: cellRender,
            numberFormatter,
            cellStyle: cellstyle

        }, {
            field: "firstTables",
            minWidth: 200,
            maxWidth: 200,
            editable: canEdit,
            cellRenderer: cellRender,
            numberFormatter,
            cellStyle: cellstyle
        }],
        "自填数据": [{
            field: "first",
            minWidth: 450,
            maxWidth: 450
        }, {
            field: "firstTable",
            editable: canEdit,
            minWidth: 100,
            maxWidth: 100,
            cellRenderer: cellRender

        }, {
            field: "firstTables",
            minWidth: 100,
            maxWidth: 100,
            editable: canEdit,
            cellRenderer: cellRender
        },],
        "现金流量表补充资料": [
            {
                field: "first",
                minWidth: 450,
                maxWidth: 450,
                cellStyle: cellStongStyle,
                valueFormatter

            }, {
                field: "firstTable",
                editable: canEdit,
                minWidth: 200,
                maxWidth: 200,
                cellRenderer: cellRender,
                numberFormatter,
                cellStyle: cellstyle

            }, {
                field: "firstTables",
                minWidth: 200,
                maxWidth: 200,
                editable: canEdit,
                cellRenderer: cellRender,
                numberFormatter,
                cellStyle: cellstyle
            },
        ]
    }
    //三年审计报告列头数据
    let threYearColumn: any = {
        "doubuleTable": [
            {
                field: "first",
                minWidth: 250,
                maxWidth: 250,
                cellClass: "cell-wrap-text",
                autoHeight: true, valueFormatter
            }, {
                field: "firstTable",
                editable: canEdit,
                minWidth: 150,
                maxWidth: 150,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter

            }, {
                field: "firstTables",
                minWidth: 150,
                maxWidth: 150,
                editable: canEdit,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter
            }, , {
                field: "firsttables",
                minWidth: 150,
                maxWidth: 150,
                editable: canEdit,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter
            },
            {
                field: "second",
                minWidth: 250,
                maxWidth: 250,
                valueFormatter: valueFormatter,
                cellClass: "cell-wrap-text",
                autoHeight: true,
            }, {
                field: "secondTable",
                minWidth: 150,
                maxWidth: 150,
                editable: canEdit,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter
            }, {
                field: "secondTables",
                minWidth: 150,
                maxWidth: 150,
                editable: canEdit,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter
            }, , {
                field: "secondtables",
                minWidth: 150,
                maxWidth: 150,
                editable: canEdit,
                cellRenderer: cellRender,
                cellStyle: cellstyle,
                numberFormatter
            }
        ],
        "oneTable": [{
            field: "first",
            minWidth: 375,
            maxWidth: 375, valueFormatter
        }, {
            field: "firstTable",
            editable: canEdit,
            minWidth: 200,
            maxWidth: 200,
            cellRenderer: cellRender,
            cellStyle: cellstyle,
            numberFormatter

        }, {
            field: "firstTables",
            minWidth: 200,
            maxWidth: 200,
            editable: canEdit,
            cellRenderer: cellRender,
            cellStyle: cellstyle,
            numberFormatter
        }, {
            field: "firsttables",
            minWidth: 200,
            maxWidth: 200,
            editable: canEdit,
            cellRenderer: cellRender,
            cellStyle: cellstyle,
            numberFormatter
        }],
        "自填数据": [{
            field: "first",
            minWidth: 450,
            maxWidth: 450
        }, {
            field: "firstTable",
            editable: canEdit,
            minWidth: 100,
            maxWidth: 100,
            cellRenderer: cellRender,
            numberFormatter

        }, {
            field: "firstTables",
            minWidth: 100,
            maxWidth: 100,
            editable: canEdit,
            cellRenderer: cellRender,
            numberFormatter
        }, {
            field: "firsttables",
            minWidth: 100,
            maxWidth: 100,
            editable: canEdit,
            cellRenderer: cellRender,
            numberFormatter
        }],
        "现金流量表补充资料": [
            {
                field: "first",
                minWidth: 450,
                maxWidth: 450
            }, {
                field: "firstTable",
                editable: canEdit,
                minWidth: 200,
                maxWidth: 200,
                cellRenderer: cellRender,
                numberFormatter,
                cellStyle: cellstyle

            }, {
                field: "firstTables",
                minWidth: 200,
                maxWidth: 200,
                editable: canEdit,
                cellRenderer: cellRender,
                numberFormatter,
                cellStyle: cellstyle
            }, {
                field: "firsttables",
                minWidth: 200,
                maxWidth: 200,
                editable: canEdit,
                cellRenderer: cellRender,
                numberFormatter,
                cellStyle: cellstyle
            }
        ]
    }
    //const
    //是否为三年审计报告
    let column: any = []
    const isThreeYearReport = (data: string) => {
        if (isThree) {

            column = threYearColumn[data]
            setColumRef(threYearColumn[data])
        } else {
            //   console.log(data, columnData[data]);

            column = columnData[data]
            setColumRef(columnData[data])
        }
    }
    //修改是否可见编辑
    //切换编辑
    const switchChange = (checked: any) => {
        setIsEdit(checked)
    }
    const defaultColDef = useMemo(() => {
        return {
            flex: 1,
            minWidth: 150,
        };
    }, []);

    const upDateData = async () => {
        if (errorRow.length) {
            message.error({
                content: `第 ${errorRow[0]} 行 数据校验校验错误：数据格式不对`,
                style: {
                    color: "rgb(228,116,112)",
                }
            })
        } else if (!(defaultData.length)) {
            message.warn("您未修改数据")
        } else {
            //   console.log(changeValueList);

            let values: any = {}
            changeValueList.forEach((item: any) => {
                Object.keys(item).forEach((Item: any) => {
                    if (Item != "key") {
                        values[Item] = item[Item]
                    }
                })
            })
            let data = {
                period: "first",
                projectId,
                data: {
                    kind: columnType,
                    values
                }
            }
            let res = await parseService.updateResult(data)
            if (res.detail = "更新完成") {
                message.success("更新成功").then(() => {
                    window.localStorage.setItem("currentKey", columnType)
                    window.location.reload()
                })
            }
        }

    }

    //组件挂载重置编辑
    useEffect(() => {
        setIsEdit(false)
        setErrorOpen(false)
        setNeedCommit(false)
        dispatch(setErrorList([]))
    }, [columnType])
    useEffect(() => {
        if (columnType == "审计意见解析") {
            column = columnData[columnType]
            setColumRef(columnData[columnType])
        } else if (["合并资产负债表", "母公司资产负债表"].some((item: string) => item == columnType)) {
            isThreeYearReport("doubuleTable")
        } else if (["合并利润表", "合并现金流量表", "母公司利润表", "母公司现金流量表"].some((item: string) => item == columnType)) {
            isThreeYearReport("oneTable")
        } else if (columnType == "自填数据") {
            isThreeYearReport("自填数据")
        } else if (columnType == "现金流量表补充资料") {
            isThreeYearReport("现金流量表补充资料")
        }
        //设置表格宽度
        if (column && column.length) {
            let width = 0
            column.forEach((item: any) => {
                if (item.maxWidth) {
                    width += item.maxWidth
                }
            })
            setRowWidht(width + 2)
        }
    }, [columnType, isEdit])
    return (
        <div >
            <div>

                <div className={"Buttonlist"}>
                    {columnType != "附注解析" ? <div className={"isEdit"}><span
                        style={{
                            color: isEdit ? "#000" : "rgb(89,157,248)",
                            fontWeight: 600
                        }} onClick={() => {
                            setIsEdit(!isEdit)
                        }}>查看</span><Switch
                            checked={isEdit}
                            onChange={switchChange}
                            style={{
                                marginRight: "5px",
                                marginLeft: "5px"
                            }} /> <span style={{
                                color: isEdit ? "rgb(89,157,248)" : "#000",
                                fontWeight: 600
                            }} onClick={() => {
                                setIsEdit(!isEdit)
                            }}>编辑</span></div> : ""}
                    {needCommit ? <Button type="primary"
                        onClick={upDateData}
                        style={{
                            marginRight: 20
                        }}
                    >保存修改并重新校对</Button> : ""}
                    {
                        (errorList[columnType] && errorList[columnType].length) || (errorList["合并" + columnType] && errorList["合并" + columnType].length) ? <div>
                            {errorOpen ? <Button type="primary" danger onClick={() => {
                                setErrorOpen(false)
                                dispatch(setErrorList([]))
                            }}><UpOutlined />收起勾稽关系</Button> : <Button type="primary" danger onClick={() => {
                                setErrorOpen(true)
                            }}><DownOutlined />展开勾稽关系</Button>}
                        </div> : ""
                    }
                </div>
                {/* 勾稽关系错误列表 */}

                {errorOpen && ((errorList[columnType] && errorList[columnType].length) || (errorList["合并" + columnType] && errorList["合并" + columnType].length)) ? <div className='errorTable'

                >
                    <div className='ag-theme-alpine'
                        style={{
                            width: "100%",
                            height: "100%",
                            overflow: "hidden"
                        }}
                    >
                        <AgGridReact

                            rowSelection={'single'}
                            columnDefs={errorColRef}
                            rowData={errorList[columnType] || errorList["合并" + columnType]}
                            onRowClicked={(e: any) => {
                                dispatch(setErrorList(e.data.error_key_list))
                                //  dispatch(setErrorList(e.data.error_key_list))
                            }}

                        >
                        </AgGridReact>
å
                    </div>
                </div> : ""

                }
                {/* 解析结果表格解析 */}
                <div style={containerStyle} >
                    <div
                        style={
                            { width: rowWidht }
                        }
                        className="ag-theme-alpine"
                    >
                        <AgGridReact
                            ref={gridRef}
                            headerHeight={0}
                            rowData={datasource}
                            columnDefs={columnRef}
                            defaultColDef={defaultColDef}
                            rowHeight={rowHeight}
                            domLayout='autoHeight'
                            onCellEditingStarted={(e) => {
                                let mayBeChangeRow: any = [...defaultData]
                                if (mayBeChangeRow.some((item: any) => item.key == e.data.key)) {
                                } else {
                                    mayBeChangeRow.push(e.data)
                                    dispatch(setDefaultData(mayBeChangeRow))
                                }
                            }}
                            onCellValueChanged={(e: any) => {


                                setNeedCommit(true)
                                if (e.value != e.value * 1 && e.value != "") { //输入数据有错误
                                    let error: any = errorRow
                                    error.push(e.rowIndex + 1)
                                    error.sort((a: number, b: number) => { return a - b })
                                    setErrorRow(error)
                                } else {


                                    let error: any = errorRow.filter((item: number) => item != e.rowIndex + 1)
                                    setErrorRow(error)
                                    let values: any = {}
                                    values.key = e.data.key
                                    values[e.data.first.trim() + "-本期"] = e.data.firstTable
                                    values[e.data.first.trim() + "-上期"] = e.data.firstTables
                                    if (isThree) {
                                        values[e.data.first.trim() + "-上上期"] = e.data.firsttables
                                    }
                                    if (e.data.second) {
                                        values[e.data.second.trim() + "-本期"] = e.data.secondTable
                                        values[e.data.second.trim() + "-上期"] = e.data.secondTables
                                        if (isThree) {
                                            values[e.data.second.trim() + "-上上期"] = e.data.secondtables
                                        }
                                    }
                                    let data = [...changeValueList.filter((item: any) => item.key != values.key), values]
                                    dispatch(setChangeVauleList(data))
                                }
                            }}
                            onCellEditingStopped={(e) => {
                                if (defaultData.some((item: any) => JSON.stringify(item) == JSON.stringify(e.data))) {
                                    let mayBeChangeRow = defaultData.filter((item: any) => JSON.stringify(item) !== JSON.stringify(e.data))
                                    dispatch(setDefaultData(mayBeChangeRow))

                                }

                            }}
                        ></AgGridReact>
                    </div>
                </div>
            </div>
        </div >
    )
}
